#include "PatchStomper/StomperModel.h"
#include "PatchStomper/TextureFileInfo.h"
#include "PatchStomper/ToolElements/TextureInfoElement.h"
#include "StompedReality/Core/FileSystem.h"
#include "StompedReality/Core/TypeSystem/TypeSystem.h"
namespace PatchStomper
{

TextureInfoElement::TextureInfoElement( StomperLib::BaseLayout* layout, StompedReality::IGame* game )
  : StomperLib::ToolElement( layout, game, NULL )
{
}

TextureInfoElement::~TextureInfoElement( )
{
}

void TextureInfoElement::OnSelectFile( Gwen::Event::Info info )
{
  this->SaveCurrentTextureInfo( );
  this->CreateOrOpenTextureInfo( info.String.Get( ));
}

void TextureInfoElement::SaveCurrentTextureInfo( )
{
  std::string textureInfoFile = this->Model->GetBaseFileName( this->Model->CurrentWorkingFile );
  textureInfoFile.append( ".info" );

  auto stomperModel = (PatchStomper::StomperModel*) this->Model;

  if (stomperModel->CurrentTextureInfo == NULL)
    return;

  this->m_Game->getFileSystem( )->saveJson<PatchStomper::TextureFileInfo>( stomperModel->CurrentTextureInfo,
                                                                           textureInfoFile );
}

void TextureInfoElement::CreateOrOpenTextureInfo( std::string textureFile )
{
  std::string textureInfoFile = this->Model->GetBaseFileName( textureFile );
  textureInfoFile.append( ".info" );

  auto stomperModel = (PatchStomper::StomperModel*)this->Model;

  auto textureInfo = new PatchStomper::TextureFileInfo( );

  if (this->m_Game->getFileSystem( )->existsFile( textureInfoFile ))
  {
    textureInfo = new PatchStomper::TextureFileInfo( );
    this->m_Game->getFileSystem( )->readJsonObject<PatchStomper::TextureFileInfo>( textureInfo, textureInfoFile );
  }
  else {
    textureInfo->Global = false;
    textureInfo->FileName = textureFile;
    textureInfo->ID = stomperModel->NextTextureID;

    stomperModel->NextTextureID++;
  }
  stomperModel->CurrentTextureInfo = textureInfo;

  //stomperModel->AddTextureItem( textureInfo->FileName, textureInfo );
}

}

